package com.ringtheweb.web.action;

import java.util.List;

import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Out;
import org.jboss.seam.annotations.bpm.CreateProcess;
import org.jboss.seam.annotations.bpm.EndTask;
import org.jboss.seam.annotations.bpm.StartTask;
import org.jboss.seam.annotations.bpm.Transition;
import org.jboss.seam.contexts.Contexts;
import org.jboss.seam.faces.Renderer;
import org.jboss.seam.log.Log;

import com.ringtheweb.model.PhoneNumber;
import com.ringtheweb.model.RoleType;
import com.ringtheweb.model.User;
import com.ringtheweb.persistence.dao.IUserDAO;
import com.ringtheweb.web.interceptor.annotation.JbpmHandler;

/**
 * Registration BusinessProcess methods
 * @author Luc
 *
 */
@Name("registration")
@JbpmHandler
public class RegistrationProcessAction {
	
	@In(scope=ScopeType.BUSINESS_PROCESS,required=false)  @Out(scope=ScopeType.BUSINESS_PROCESS,required=false) User userToRegister;
	
	@In("#{userDAO}") IUserDAO userDAO;
    
    @Out(scope=ScopeType.BUSINESS_PROCESS,required=false)PhoneNumber phoneToRegister;
	
	@In(create=true)Renderer renderer;
	
    @Logger Log logger;
    
    
	@CreateProcess(definition="registration")
    public void startRegistration(User user) {
    	userToRegister = user;
    	phoneToRegister = user.getPhoneNumbers().iterator().next();
    	
    }
	
    @Transition("toAdministratorApproval")
	public void sendAdminApproval() {
		List<User> adminUsers = userDAO.findByRoleName(RoleType.ADMIN.name());
		for(User adminUser:adminUsers) {
			Contexts.getEventContext().set("adminUser", adminUser);
			logger.info("Sending email to #0 for user #1", adminUser.getEmail(),userToRegister.getLoginName());
			renderer.render("/email/adminApproval.xhtml");
		}
		
	}


	@Transition("end")
	public void sendUserResponse(boolean accept) {
		logger.info("Sending email to user #0", userToRegister.getLoginName());
		if (accept) {
			renderer.render("/email/registrationApproved.xhtml");
		}
		else {
			renderer.render("/email/registrationRejected.xhtml");
		}
		
	}
	
    @StartTask @EndTask(transition="approve")
    public void approve() {
    }
    
    @StartTask @EndTask(transition="reject")
    public void reject(){
    }
    
    
    public IUserDAO getUserDAO() {
		return userDAO;
	}

	public void setUserDAO(IUserDAO userDAO) {
		this.userDAO = userDAO;
	}

}
